<template>
  <section class="recent-visits" v-if="visits.length > 0">
    <div class="section-header">
      <h2>最近访问</h2>
      <button class="clear-btn" @click="handleClear">清空</button>
    </div>
    <div class="recent-list">
      <div 
        class="recent-item" 
        v-for="item in visits" 
        :key="item.code"
        @click="handleSelect(item)"
      >
        <div class="recent-icon">📍</div>
        <div class="recent-info">
          <span class="recent-name">{{ item.name }}</span>
          <span class="recent-code">{{ item.code }}</span>
        </div>
        <span class="recent-time">{{ item.visitTime }}</span>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'

const STORAGE_KEY = 'station_recent_visits'
const MAX_ITEMS = 10

const props = defineProps({
  // 允许外部控制最大数量
  maxItems: {
    type: Number,
    default: MAX_ITEMS
  }
})

const emit = defineEmits(['select', 'clear'])

const visits = ref([])

// 从本地存储加载
function loadFromStorage() {
  try {
    const stored = uni.getStorageSync(STORAGE_KEY)
    if (stored) {
      visits.value = JSON.parse(stored)
    }
  } catch (e) {
    console.error('加载最近访问记录失败:', e)
    visits.value = []
  }
}

// 保存到本地存储
function saveToStorage() {
  try {
    uni.setStorageSync(STORAGE_KEY, JSON.stringify(visits.value))
  } catch (e) {
    console.error('保存最近访问记录失败:', e)
  }
}

// 添加访问记录（供父组件调用）
function addVisit(item) {
  const index = visits.value.findIndex(v => v.code === item.code)
  if (index > -1) {
    visits.value.splice(index, 1)
  }
  visits.value.unshift({
    code: item.code,
    name: item.name || item.stnm,
    visitTime: formatTime(new Date())
  })
  if (visits.value.length > props.maxItems) {
    visits.value = visits.value.slice(0, props.maxItems)
  }
  saveToStorage()
}

// 格式化时间
function formatTime(date) {
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 172800000) return '昨天'
  
  return `${date.getMonth() + 1}-${date.getDate()}`
}

function handleSelect(item) {
  emit('select', item)
}

function handleClear() {
  visits.value = []
  saveToStorage()
  emit('clear')
}

onMounted(() => {
  loadFromStorage()
})

// 暴露方法供父组件调用
defineExpose({
  addVisit,
  visits
})
</script>

<style scoped>
.recent-visits {
  width: 100%;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #f1f5f9;
  margin: 0;
}

.clear-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: none;
  border: none;
  color: #64748b;
  font-size: 13px;
  cursor: pointer;
  transition: color 0.2s;
}

.clear-btn:hover {
  color: #ef4444;
}

.recent-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.recent-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 14px 18px;
  background: rgba(255, 255, 255, 0.04);
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.recent-item:hover {
  background: rgba(255, 255, 255, 0.08);
}

.recent-icon {
  font-size: 20px;
}

.recent-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.recent-name {
  font-size: 14px;
  color: #e2e8f0;
}

.recent-code {
  font-size: 12px;
  color: #64748b;
  font-family: 'Monaco', 'Consolas', monospace;
}

.recent-time {
  font-size: 12px;
  color: #64748b;
}
</style>

